Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Spring Boot - run() Method


So far, we have seen that we have written a basic Spring Boot Application.


Example :



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyFirstApplication {

   public static void main(String[] args) {
   
      SpringApplication.run(MyFirstApplication.class, args);
   }
}



And most importantly, there is just this run() method that ran the Spring Boot Application.


SpringApplication.run(MyFirstApplication.class, args);

Now, if you notice, there is this class SpringApplication that contains this static method called run().


This run() method of Spring runs on startup. Which means, when Spring Boot starts up, this run() method is executed.


The run() method takes these two arguments, first one is the class MyFirstApplication.class and the other is the command line argument(i.e. args) that we have passed to the main() method.


Now, internally this run() method performs a lot of task, so that you don't have to write those stuff yourself.


So, the run() method performs the below tasks :

  1. Sets up the initial configuration.


    The run() method sets up the initial configuration those are needed for Spring Boot to start. So that you don't have to configure them all by yourself.

  2. Starts the Application Context of Spring.


    You can consider the Application Context as the main container for Spring. In Spring when you define classes, those classes(Also called as beans) are managed by the Application Context. And the run() method creates this Application Context.

  3. Scans Class Path


    Do you remember how spring works. Here's a quick recap. Spring contains Controller classes that are marked with @Controller annotation and also there are Service classes annotated with @Service annotation.

    Now, what run() method does is, Scans the Class Path and figures out which all classes are marked with @Controller annotation or @Service annotation or something else. Based on that Spring takes the decision that how they should behave.

  4. Downloads and starts Tomcat Server.


    Since, this is a web application we are trying to build, we need a server to deploy and start the application. And in this case Tomcat Server is used.

    But have we downloaded the Tomcat Server?

    No! We haven't.

    Well! Even in this case Spring Boot has downloaded and started the Tomcat server for us.

And this entire thing is done by the magical run() method,


SpringApplication.run(MyFirstApplication.class, args);